<template>
  <div class="right-container">
    <el-tabs v-model="activeName" class="right-tabs" @tab-change="onTabChange">
      <el-tab-pane label="学生详情" name="stuDetail">
        <StudentDetail
          v-if="activeName === 'stuDetail'"
          :isLoading="isLoading"
        ></StudentDetail>
      </el-tab-pane>
      <el-tab-pane label="共性错题" name="genDetail">
        <GeneralityTopic
          v-if="activeName === 'genDetail'"
          :isLoading="isLoading"
          @generalityNextPage="handleGeneralitNext"
          @get-generality-topic="handleGetGeneralityTopic"
          @refresh-common-list="refreshCommonList"
          :topicData="generalityTopic"
          :total="commonTotal"
          :isPushing="isPushing"
          from="common-wrong"
          @close-pushing="isPushing = false"
        ></GeneralityTopic>
      </el-tab-pane>
      <el-tab-pane label="知识点题目" name="knowTopic">
        <KnowledgeTopic
          v-if="activeName === 'knowTopic'"
          :isLoading="isLoading"
          @get-knowledge-topic="handleGetKnowledgeTopic"
          @knowledgeNextPage="handleKnowledgeNext"
          :topicData="knowledgeTopic"
        ></KnowledgeTopic>
      </el-tab-pane>
    </el-tabs>
    <p v-if="activeName === 'genDetail'" class="is-pushing">
      <el-popover placement="bottom-start" trigger="hover" width="15vw">
        <template #reference>
          <el-icon>
            <Warning />
          </el-icon>
        </template>
        <template #default>
          <div class="content">
            <p>将为选入试题篮的错题智能推荐举一反三的题。</p>
            <p>每道题推荐3道举一反三的题</p>
          </div>
        </template> </el-popover
      >智能推题
      <el-switch
        :disabled="!pushingEnabled"
        v-model="isPushing"
        @mouseenter="onMouseEnter"
      />
    </p>
    <!-- <div class="title">学生详情</div> -->
  </div>
</template>
<script setup>
import { ref, watch, computed, onBeforeMount } from 'vue'
import { useRoute } from 'vue-router'
import StudentDetail from './StudentDetail.vue'
import KnowledgeTopic from './KnowledgeTopic.vue'
import GeneralityTopic from './GeneralityTopic.vue'
import {
  getTopicList,
  getQuestionList,
  getCourseList
} from '@/apis/knowledge/index'
import { Warning } from '@element-plus/icons-vue'
import { useTaskStore } from '@/stores/task'
import { useKnowledgeStore } from '@/stores/knowledge-store'
import { ElMessage } from 'element-plus'
// import { storeToRefs } from 'pinia'

const knowledgeStore = useKnowledgeStore()
const taskStore = useTaskStore()
const activeName = ref('stuDetail')
const route = useRoute()
const classType = ref(0)
const startTime = ref(0)
const endTime = ref(0)
const subjectId = ref(0)
const classId = ref('')
const knowledgeName = ref('')
// const knowledgeIds = ref([])
const orderBy = ref(1) // 1：时间（id）；-1：时间逆序；2：正确率；-2：正确率逆序
let page_generality = 1
let page_size_generality = 10
let isEnd_generality = false
let page_knowledge = 1
let page_size_knowledge = 10
let isEnd_knowledge = false
const generalityTopic = ref([])
const knowledgeTopic = ref([])
const commonTotal = ref(0)
const isLoading = ref(false)

const onTabChange = val => {
  isPushing.value = false
}

onBeforeMount(async () => {
  if (route.query.task_id) {
    activeName.value = 'genDetail'
  }
  const { name, start_time, end_time, subject_id, class_id, class_type } =
    route.query
  // const { knowledgeIdsArr } = storeToRefs(knowledgeStore)
  classType.value = class_type
  startTime.value = start_time
  endTime.value = end_time
  subjectId.value = subject_id
  classId.value = class_id
  knowledgeName.value = name
  // knowledgeIds.value = JSON.parse(knowledgeIdsArr.value)
})
// 监听知识点树的变化，重新获取共性、知识点错题列表，先不管性能问题  他急着要
watch(
  () => knowledgeStore.knowledgeTree,
  async () => {
    // 重置共性错题列表
    page_generality = 1
    page_size_generality = 10
    isEnd_generality = false
    generalityTopic.value = []
    const geneData = await handleGetGeneralityTopicList()
    if (!geneData.total) {
      generalityTopic.value = []
    }

    // 重置知识点错题列表
    page_knowledge = 1
    page_size_knowledge = 10
    isEnd_knowledge = false
    knowledgeTopic.value = []
    const knowledgeData = await handleGetKnowledgeTopicList()

    if (!knowledgeData.total) {
      knowledgeTopic.value = []
    }
  }
)

const refreshCommonList = async params => {
  page_generality = 1
  isEnd_generality = false
  generalityTopic.value = []
  const geneData = await handleGetGeneralityTopicList(params)
  if (!geneData.total) {
    generalityTopic.value = []
  }
}

const handleGetGeneralityTopic = async () => {
  await handleGetGeneralityTopicList({
    task_id: route.query.origin_task_id ? [route.query.origin_task_id] : []
  })
}
async function handleGeneralitNext(params) {
  console.log(isEnd_generality)

  if (isEnd_generality) {
    ElMessage.warning('没有更多数据了')
    return
  }
  page_generality = page_generality + 1
  await handleGetGeneralityTopicList(params)
}

const handleGetKnowledgeTopic = async () => {
  await handleGetKnowledgeTopicList()
}
async function handleKnowledgeNext() {
  if (isEnd_knowledge) {
    ElMessage.warning('没有更多数据了')
    return
  }
  page_knowledge = page_knowledge + 1
  await handleGetKnowledgeTopicList()
}

// 提取知识点树的所有id，请求需要使用
function extractIds(node) {
  let ids = []

  function traverse(node) {
    if (node?.id) {
      ids.push(node.id)
    }
    if (node?.children && node?.children.length > 0) {
      node.children.forEach(child => traverse(child))
    }
  }
  traverse(node)
  return ids
}

// 共性
async function handleGetGeneralityTopicList(payload) {
  console.log(route)
  if (isEnd_generality) return
  isLoading.value = true
  console.log(isLoading.value)

  const curKnowledgeIds = extractIds(knowledgeStore.knowledgeTree)
  const params = {
    class_id: classId.value,
    class_type: Number(classType.value),
    start_time: Number(startTime.value),
    end_time: Number(endTime.value),
    subject_id: Number(subjectId.value),
    order_by: orderBy.value,
    knowledge_ids: curKnowledgeIds,
    page: page_generality,
    size: page_size_generality,
    ...payload
  }
  if (knowledgeStore.selectedStudent.length) {
    params.student_id = knowledgeStore.selectedStudent.map(
      item => item.student_id
    )
  }
  const { data, msg } = await getTopicList(params)
  commonTotal.value = data.total || 0
  if (msg == 'OK') {
    if (data.total == 0) {
      isLoading.value = false
      isEnd_generality = true
      return data
    }
    generalityTopic.value = generalityTopic.value.concat(data.data)
    if (data.data.length < page_size_generality) {
      isEnd_generality = true
    }
  }
  isLoading.value = false
  return data
}

async function handleGetKnowledgeTopicList() {
  console.log(knowledgeStore.knowledgeTree)
  if (isEnd_knowledge) return
  isLoading.value = true
  const { data: courseData } = await getCourseList({
    stage: route.query.stage_id,
    subject: route.query.subject_id
  })

  const { data } = await getQuestionList({
    page: page_knowledge,
    page_size: page_size_knowledge,
    course_id: courseData[0].id,
    keypoint: knowledgeStore.knowledgeTree?.id
  })
  console.log(data, 'getQuestionList')
  if (data?.total == 0) {
    isEnd_knowledge = true
    isLoading.value = false
    return data
  }

  knowledgeTopic.value = knowledgeTopic.value.concat(data?.list)
  if (data?.list.length < page_size_knowledge) {
    isEnd_knowledge = true
  }
  isLoading.value = false
}

// 智能推题
const isPushing = ref(false)
const pushingEnabled = computed(() => {
  for (let index = 0; index < taskStore.taskList.length; index++) {
    const element = taskStore.taskList[index]
    const res = generalityTopic.value.find(
      item1 => item1.question.id === element.topic_id
    )
    if (res) {
      return true
    }
  }
  return false
})

const onMouseEnter = () => {
  if (!pushingEnabled.value) {
    ElMessage.warning('请先将题目加入试题篮！')
  }
}

watch(
  () => taskStore.taskList.length,
  val => {
    if (!val) isPushing.value = false
  }
)
</script>
<style lang="less" scoped>
.right-container {
  box-sizing: border-box;
  position: relative;
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 21px;
  background-color: #fff;
  border-radius: 14px;
  padding: 16px;
  overflow: hidden;

  .is-pushing {
    position: absolute;
    display: flex;
    align-items: center;
    gap: 10px;
    right: 30px;
    top: 30px;
    color: @color-brand-regular;
  }

  .title {
    font-size: 18px;
    font-weight: 700;
  }

  :deep(.right-tabs) {
    height: 100%;
    display: flex;
    // flex-direction: column;

    .el-tabs__nav-wrap::after {
      display: none;
    }

    .el-tabs__content {
      flex: 1;

      .el-tab-pane {
        height: 100%;
      }
    }

    .el-tabs__item {
      font-size: 18px;
      color: #333;
      opacity: 0.5;
      height: 52px;
    }

    .is-active {
      opacity: 1;
      font-weight: bold;
    }

    .el-tabs__active-bar {
      background-color: #333;
      height: 3px;
    }
  }
}
</style>
